<?php
/**
 * The Router class
 */
class LyRouter
{
	protected  $action;
	protected  $options = array();
	protected  $params;
	function setOptions($options){
		$this->options = array_merge($this->options,$options);
	}
	public function init()
	{
		$action = '';
		// index.php?action=action
		if (isset($_REQUEST['action']))
		{
			$action = $_REQUEST['action'];
		}
		// index.php/action/
		if ( isset($_SERVER['PATH_INFO']))
		{
			$pathInfo = str_replace($this->options['urlSuffix'],'',$_SERVER['PATH_INFO']);
			$pathInfo = strtolower($pathInfo);
			$pathInfo = trim($pathInfo,'/\\ ');
			$arrayPathInfo = explode('/',$pathInfo);
			if(empty($action)){
				$action = array_shift($arrayPathInfo);
			}
			if(!empty($arrayPathInfo)){
				$count = count($arrayPathInfo);
				for($i=0;$i<$count-1;$i+=2){
					$this->params[$arrayPathInfo[$i]] = $arrayPathInfo[$i+1];
				}
			}
		}
		// action 名字只能大小写字母 数字 . - _
		if (!empty($action) && !preg_match('/^[a-zA-Z0-9\.\-_]+$/', $action))
		{
			throw new Exception("Action name is illegal: {$action}");

		}
		if(!empty($action) && isset($this->options[$action.'_alias'])){
			$action = $this->options[$action.'_alias'];
		}
		$this->action = $action ? $action : $this->options['defaultAction'];
	}
	function getAction(){
		return $this->action;
	}
	function getParams($name = null){
		if(null === $name){
			return $this->params;
		}else{
			$name = trim(strtolower($name));
			return isset($this->params[$name])?$this->params[$name]:array();
		}
	}
}
